﻿Public Class ValidarUsuarioCierre 

    Private Sub SimpleButton1_Click(sender As System.Object, e As System.EventArgs) Handles btGenerar.Click
        If ValidaUsuario() = 0 Then
            Try
                If FacturasTableAdapter1.Fill(DbFireAndIceDataSet1.facturas) Then
                    Dim idcierre As Integer
                    If CierrecajaTableAdapter1.ScalarQueryObtieneUltimoId() Then
                        idcierre = CierrecajaTableAdapter1.ScalarQueryObtieneUltimoId() + 1
                    Else
                        idcierre = 1
                    End If

                    Dim ticketinicial As Integer
                    If CierrecajaTableAdapter1.ScalarQueryUltimoCierreTicketFinal(My.Computer.Name) Then
                        ticketinicial = CierrecajaTableAdapter1.ScalarQueryUltimoCierreTicketFinal(My.Computer.Name) + 1
                    Else
                        If FacturasTableAdapter1.ScalarQueryObtienePrimerTicketPorCaja(My.Computer.Name) Then
                            ticketinicial = FacturasTableAdapter1.ScalarQueryObtienePrimerTicketPorCaja(My.Computer.Name)
                        Else
                            ticketinicial = FacturasTableAdapter1.ScalarQueryObtieneUltimoNumFactura()
                        End If
                    End If

                    Dim ticketfinal As Integer
                    If FacturasTableAdapter1.ScalarQueryObtieneUltimoNumFactura() Then
                        ticketfinal = FacturasTableAdapter1.ScalarQueryObtieneUltimoNumFactura()
                    Else
                        ticketfinal = 1
                    End If

                    Dim totaltickets As Integer
                    If FacturasTableAdapter1.ScalarQueryTotalTicketsPorCierre(My.Computer.Name, ticketinicial, ticketfinal) Then
                        totaltickets = FacturasTableAdapter1.ScalarQueryTotalTicketsPorCierre(My.Computer.Name, ticketinicial, ticketfinal)
                        totaltickets = totaltickets + 2
                    Else
                        totaltickets = 0
                    End If

                    If ticketfinal - ticketinicial < 0 Then
                        MsgBox("No ha facturado desde el último cierre.", MsgBoxStyle.Critical, "Cierre de caja no está disponible")
                    Else
                        Dim connectionstring As String = My.Forms.frmFactura.GetConnnectionString()
                        Dim conn As New Devart.Data.PostgreSql.PgSqlConnection(connectionstring)
                        Dim pc As String
                        pc = String.Format("'{0}'", My.Computer.Name) 'String.Format("{0}", My.Computer.Name)
                        Try
                            Dim totalvendido As Double
                            conn.Open()
                            Dim qTotalVendido As String = String.Format("select sum(total) from facturas where numfactura >= {0} AND numfactura <= {1} AND nula = false AND nombrepc = {2};", Str(ticketinicial), Str(ticketfinal), pc)
                            Dim cmmTotalVendido As New Devart.Data.PostgreSql.PgSqlCommand(qTotalVendido, conn)
                            totalvendido = cmmTotalVendido.ExecuteScalar()
                            conn.Close()

                            CierrecajaTableAdapter1.InsertQuerySinEfectivoReal(My.Forms.MDI.Iduser.Caption, Today, TimeOfDay, _
                                                                           1, 1, idcierre, ticketinicial, ticketfinal, _
                                                                           My.Computer.Name, totaltickets, totalvendido)
                        Catch ex As Exception
                            AlertControl1.AppearanceCaption.ForeColor = Color.Red
                            AlertControl1.Show(Me, "Error", "Ha ocurrido un error al calcular el total vendido.")
                            TlogTableAdapter1.InsertQueryLogs(TlogTableAdapter1.ScalarQueryCountLogs + 1, My.Forms.MDI.Iduser.Caption, _
                                                              My.Resources.StringGlobal.prgAngely, _
                                                              "Error en query para calcular el total vendido, ValidarUsuarioCierre.", _
                                                              ex.Message, My.Resources.StringGlobal.mdlFacturacion, Date.Today, _
                                                              TimeOfDay.TimeOfDay.ToString, My.Computer.Name, Name.ToString, sender.GetType.FullName.ToString)
                        End Try

                        Try
                            conn.Open()
                            Dim query As String = String.Format("select calcula_cierre_caja({0},{1},{2},{3});", Str(idcierre), Str(ticketinicial), Str(ticketfinal), pc)
                            Dim comando As New Devart.Data.PostgreSql.PgSqlCommand(query, conn)
                            comando.ExecuteNonQuery()
                            conn.Close()
                        Catch ex As Exception
                            AlertControl1.AppearanceCaption.ForeColor = Color.Red
                            AlertControl1.Show(Me, "Error", "Ha ocurrido un error mientras se calculaba el cierre de caja.")
                            TlogTableAdapter1.InsertQueryLogs(TlogTableAdapter1.ScalarQueryCountLogs + 1, My.Forms.MDI.Iduser.Caption, _
                                                              My.Resources.StringGlobal.prgAngely, _
                                                              "Error en la llamada al procedimiento calcula_cierre_caja() en ValidarUsuarioCierre.", _
                                                              ex.Message, My.Resources.StringGlobal.mdlFacturacion, Date.Today, _
                                                              TimeOfDay.TimeOfDay.ToString, My.Computer.Name, Name.ToString, sender.GetType.FullName.ToString)
                        End Try


                        Dim report As New rptCierre
                        report.VreportecierreTableAdapter.FillById(report.DbFireAndIceDataSet1.vreportecierre, idcierre)
                        Dim totalespago As Integer = report.VreportecierreTableAdapter.ScalarQueryObtieneTotalTiposPago(idcierre)
                        report.PageHeight = report.PageHeight + report.Bands(DevExpress.XtraReports.UI.BandKind.Detail).HeightF * (totalespago - 1)
                        report.Print()
                        'report.ShowPreview()

                        Dim reportmov As New rptMovimientos
                        If reportmov.VreportemovimientosTableAdapter1.FillByCaja(reportmov.DbFireAndIceDataSet1.vreportemovimientos, ticketinicial, ticketfinal, My.Computer.Name) Then
                            reportmov.VreportemovimientosTableAdapter1.FillByCaja(reportmov.DbFireAndIceDataSet1.vreportemovimientos, ticketinicial, ticketfinal, My.Computer.Name)
                            'reportmov.ShowPreview()
                            reportmov.Print()
                        Else
                            Dim reportevacio As New rptMovimientosVACIO
                            'reportevacio.ShowPreview()
                            reportevacio.Print()
                        End If

                        AlertControl1.AppearanceCaption.ForeColor = Color.Green
                        AlertControl1.Show(Me, "Notificación", "Se generó el cierre del día.")
                        My.Forms.frmFactura.cierrecaja = True
                        Application.Exit()
                    End If
                Else
                    MsgBox("No existen facturas en el sistema.", MsgBoxStyle.Critical, "Cierre de caja no está disponible")
                End If

            Catch ex As Exception
                AlertControl1.AppearanceCaption.ForeColor = Color.Red
                AlertControl1.Show(Me, "Error", "No se pudo generar el cierre del día.")
                TlogTableAdapter1.InsertQueryLogs(TlogTableAdapter1.ScalarQueryCountLogs + 1, My.Forms.MDI.Iduser.Caption, _
                    My.Resources.StringGlobal.prgAngely, "Sentencia para generar el cierre del día en la pantalla de Facturas", _
                    ex.Message, My.Resources.StringGlobal.mdlFacturacion, Date.Today, TimeOfDay.TimeOfDay.ToString, _
                    My.Computer.Name, Name.ToString, sender.GetType.FullName.ToString)
            End Try
        Else
            MsgBox("Contraseña incorrecta", MsgBoxStyle.Exclamation, "Notificación")
        End If
    End Sub

    Public Function ValidaUsuario()
        If tPassword.Text = "FAIcierre" Then
            Return 0
        Else
            Return 1
        End If
    End Function

    Private Sub ValidarUsuarioCierre_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        tPassword.Text = ""
        tUser.Focus()
    End Sub

    Private Sub tPassword_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles tPassword.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            btGenerar.PerformClick()
        End If
    End Sub

    Private Sub tPassword_EditValueChanged(sender As System.Object, e As System.EventArgs) Handles tPassword.EditValueChanged

    End Sub
End Class